/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.anorien.dmo.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 *
 * @author David Miguel Antunes <davidmiguel [ at ] antunes.net>
 */
public class Compression {

    public static void zipDirectoryRecur(ZipOutputStream out, String base, String dir) throws IOException {

        for (File f : new File(base + "/" + dir).listFiles()) {
            byte[] buffer = new byte[4096];
            int bytes_read;
            if (f.isDirectory()) {
                //out.putNextEntry(new ZipEntry(dir + "/" + f.getName() + "/"));
                zipDirectoryRecur(out, base, dir + "/" + f.getName());
                continue;
            }
            FileInputStream in = new FileInputStream(f);
            ZipEntry entry = new ZipEntry(dir + "/" + f.getName());
            out.putNextEntry(entry);
            while ((bytes_read = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytes_read);
            }
            in.close();
        }
    }

    public static void compressDirectory(String dir) throws IOException {
        String from = dir, to;
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream("folder.zip"));
        Compression.zipDirectoryRecur(out, from, "");
        out.close();
    }

    public static void uncompressZip(File zip, File to) throws IOException {
        try {
            final int BUFFER = 2048;
            BufferedOutputStream dest = null;
            FileInputStream fis = new FileInputStream(zip);
            ZipInputStream zis = new ZipInputStream(fis);
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                byte data[] = new byte[BUFFER];
                int count;
                File outFile = new File(to.getAbsoluteFile() + "/" + zip.getName().replace(".zip", "") + "/" + entry.getName());
                if (entry.getName().endsWith("/")) {
                    outFile.mkdirs();
                    while ((count = zis.read(data, 0, BUFFER))
                            != -1) {
                    }
                } else {
                    outFile.getParentFile().mkdirs();
                    FileOutputStream fos = new FileOutputStream(outFile);
                    dest = new BufferedOutputStream(fos, BUFFER);
                    while ((count = zis.read(data, 0, BUFFER))
                            != -1) {
                        dest.write(data, 0, count);
                    }
                    dest.flush();
                    dest.close();
                }
            }
            zis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
